import { HubConnectionBuilder, HubConnectionState } from "@microsoft/signalr"; // 导入 SignalR 库
import axios from "axios";
import { format } from "date-fns";
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
function Instore() {
  // 使用 useParams 钩子来获取动态参数
  const { port } = useParams<{ port: string }>();
  const [id, setId] = useState("0");
  //入库标签
  const [instoreLabel, setInstoreLabel] = useState("");
  //客户标签
  const [customerLabel, setCustomerLabel] = useState("");
  // 扫码失败状态
  const [scanFailed, setScanFailed] = useState(false);
  interface motreadData {
    id: string; //主键
    locNo: string; //站台号
    barcodeStatus: number; //读码状态
    barcode1: string; //条码1
    barcode1Old: string; //条码1原值
    barcode2: string; //条码2
    uniiCode: string; //UNII编码
    palletBarcode: string; //托盘条码
    describe: string; //描述
  }
  // 状态：表格数据
  const [tableData, setTableData] = useState([
    {
      sequence: 1,
      aLot: "AAD1235.1",
      code: "HB030",
      palletCode: "0409",
      time: "2025/5/15 20:00",
      status: "[标签共识成功]",
      remake: "默认数据",
    },
  ]);
  // 初始化 SignalR 连接
  const getConnection = new HubConnectionBuilder()
    .withUrl("http://192.168.3.101:3254/api/qdsignalhub") // 替换为你的 GET 接口 SignalR Hub URL
    .build();

  useEffect(() => {
    // 启动连接并设置数据接收处理
    const startConnections = async () => {
      try {
        // 检查连接状态并在必要时停止连接
        if (getConnection.state !== HubConnectionState.Disconnected) {
          await getConnection.stop(); // 停止现有连接
        }

        // 启动 SignalR 连接
        await getConnection.start();
        console.log("GET SignalR connected.");

        // 注册接收 Srm 数据的处理
        getConnection.on("ZZCNR", (data) => {
          const readData: motreadData[] = data; // 解析并断言类型
          //找到readData中port对应的LocNo的数据
          const index = readData.findIndex((item) => item.locNo == port);
          setInstoreLabel(readData[index].barcode1);
          setCustomerLabel(readData[index].barcode2);
          setId(readData[index].id);
          //分裂出数据
          const tableData: string[] = readData[index].barcode1Old.split("=");
          // 处理表格数据
          setTableData(
            tableData.map((item, no) => {
              const date = new Date(); // 获取当前日期时间
              return {
                sequence: no + 1,
                aLot: item.split(";")[3],
                code: item.split(";")[2],
                palletCode: readData[index].palletBarcode,
                time: format(date, "yyyy/MM/dd HH:mm"), // 使用date-fns的format方法格式化日期时间
                status:
                  readData[index].barcodeStatus < 90
                    ? "[标签共识成功]"
                    : "[标签共识失败]",
                remake: readData[index].describe,
              };
            })
          );
          if (readData[index].barcode1 == "") {
            console.log("标签共识失败");
            setTableData([]);
          }
          // 设置扫码失败状态
          setScanFailed(readData[index].barcodeStatus >= 90);
        });
      } catch (err) {
        console.error("Error while starting connections: ", err);
      }
    };

    startConnections();

    // 清理连接
    return () => {
      getConnection.stop(); // 停止 GET SignalR 连接
    };
  }, []);

  // 清除扫码接口
  const clearScanAPI = async (id: string) => {
    try {
      const response = await axios.post(
        "http://192.168.3.101:3254/api/motreadbarcode/cleanbarcode",
        {
          // 发送包含 id 的数据
          id,
        },
        {
          headers: {
            "Content-Type": "application/json",
            // 如果需要认证头，可以在这里添加
            // 'Authorization': 'Bearer your-token'
          },
        }
      );

      console.log("清空扫码结果成功:", response.data);
    } catch (error) {
      console.error("清空扫码结果时发生错误:", error);
    }
  };

  // 清除扫码结果的函数
  const clearScanResults = () => {
    try {
      // 调用清空扫码接口
      clearScanAPI(id);

      // 清空相关状态
      setInstoreLabel("");
      setCustomerLabel("");
      setTableData([]);
      setScanFailed(false);
    } catch (error) {
      console.error("清除扫码结果时发生错误:", error);
    }
  };

  return (
    <div
      className="app"
      style={{
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
        height: "100vh",
        width: "100vw",
        flexDirection: "column",
        backgroundColor: "white",
        color: "black",
      }}
    >
      {/* 显示端口号 */}
      <div
        style={{ marginBottom: "25px", fontSize: "40px", fontWeight: "bold" }}
      >
        端口号: {port}
      </div>

      {/* 表单 */}
      <form style={{ marginBottom: "25px" }}>
        <div
          style={{
            display: "flex",
            alignItems: "center",
            marginBottom: "25px",
          }}
        >
          <label
            style={{
              display: "flex",
              alignItems: "center",
              fontSize: "24px",
              fontWeight: "bold",
              marginRight: "10px", // 添加间距以分隔标签和按钮
            }}
          >
            {/* 放大入库标签字体 */}
            入库标签:
            <input
              type="text"
              value={instoreLabel} // 这里没有使用状态，所以不会影响
              style={{
                marginLeft: "12.5px",
                width: "500px",
                height: "37.5px",
                backgroundColor: "white",
                color: "black",
                fontSize: "18px",
                fontWeight: "bold",
              }}
              readOnly // 使文本框不可输入
            />
          </label>
          {/* 清除扫码按钮 */}
          {scanFailed && (
            <button
              onClick={clearScanResults}
              style={{
                padding: "10px 20px",
                fontSize: "20px",
                fontWeight: "bold",
                backgroundColor: "blue",
                color: "white",
                border: "none",
                cursor: "pointer",
              }}
            >
              清除扫码
            </button>
          )}
        </div>
        <div style={{ display: "flex", alignItems: "center" }}>
          <label
            style={{
              display: "flex",
              alignItems: "center",
              fontSize: "24px",
              fontWeight: "bold",
            }}
          >
            {/* 放大客户标签字体 */}
            客户标签:
            <input
              type="text"
              value={customerLabel} // 这里没有使用状态，所以不会影响
              style={{
                marginLeft: "12.5px",
                width: "500px",
                height: "37.5px",
                backgroundColor: "white",
                color: "black",
                fontSize: "18px",
                fontWeight: "bold",
              }}
              readOnly // 使文本框不可输入
            />
          </label>
        </div>
      </form>

      {/* 表格 */}
      <table
        border={1}
        cellPadding="12.5"
        width="1250px"
        style={{
          borderCollapse: "collapse",
          maxWidth: "1250px",
          fontSize: "24px",
          backgroundColor: "white",
          color: "black",
        }}
      >
        <thead>
          <tr>
            <th>序列</th>
            <th>A LOT</th>
            <th>代码</th>
            <th>托盘号</th>
            <th>时间</th>
            <th>状态</th>
            <th>备注</th>
          </tr>
        </thead>
        <tbody>
          {tableData.map((row, index) => (
            <tr
              key={index}
              style={{
                backgroundColor:
                  row.status === "[标签共识失败]" ? "red" : "white",
              }}
            >
              <td>{row.sequence}</td>
              <td>{row.aLot}</td>
              <td>{row.code}</td>
              <td>{row.palletCode}</td>
              <td>{row.time}</td>
              <td>{row.status}</td>
              <td>{row.remake}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

export default Instore;
